import { login, logout, getInfo } from '@/api/user'
import { findLeftJSON } from '@/api/company'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: null,//用户全部信息
    perms: [],//用户权限数组
    permsSimple: [],//用户权限数组中全部的路由name 用于进入页面时候的权限便捷判断
    leftJson: [],//侧边栏单位数据
    selectedComIds: [],//侧边栏已选择的
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_PERMS: (state, perms) => {
    state.perms = perms
  },
  SET_PERMS_SIMPLE: (state, permsSimple) => {
    state.permsSimple = permsSimple
  },
  SET_LEFT_JSON: (state, leftJson) => {
    state.leftJson = leftJson
  },
  SET_SELECTED_COMIDS: (state, selectedComIds) => {
    state.selectedComIds = selectedComIds
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        if (response && response.error == 0) {
          commit('SET_TOKEN', response.key)
          Cookies.set("userid", response.userid)
          setToken(response.key)
          resolve(response)
        } else {
          throw new Error(response && response.msg || "登录失败")
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }, { userid }) {
    return new Promise((resolve, reject) => {

      //递归出服务器返回的权限url
      let getPermsUrl = function (perms_, urls) {
        if (perms_.children) {
          for (let i = 0; i < perms_.children.length; i++) {
            if (perms_.children[i].url) {
              urls.push(perms_.children[i].url)
            }
            getPermsUrl(perms_.children[i], urls)
          }
        }
      }
      //对服务器返回对权限顺序重新排序 按客户需求 
      let reOrderPerms = function (perms) {
        //电子监督放到车辆管后面
        let emonitorIndex = perms.findIndex(e => e.name == "电子监督")
        let carIndex = perms.findIndex(e => e.name == "车辆管理")
        if (emonitorIndex >= 0 && emonitorIndex >= 0) {
          perms.splice(carIndex + 1, 0, ...perms.splice(emonitorIndex, 1))
        }
      }
      getInfo(userid).then(response => {
        const { userInfo, perms } = response;
        reOrderPerms(perms)
        if (!userInfo) {
          removeToken()
          reject('登录失败，请重试.')
        }
        commit('SET_NAME', userInfo.username || userInfo.loginname)
        commit('SET_USERINFO', userInfo)
        let urls = [];
        getPermsUrl({ children: perms }, urls);
        commit('SET_PERMS', perms)
        commit('SET_PERMS_SIMPLE', urls)
        commit('SET_AVATAR', 'noavatar')
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get leftjson 侧边栏单位列表
  getLeftJson({ commit }) {
    return new Promise((resolve, reject) => {
      findLeftJSON().then(response => {
        commit('SET_LEFT_JSON', response)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //左侧单位树选择后联动存储 后续相关页面的数据请求需要以选择的单位进行筛选
  setselectedComIds({ commit }, data) {
    return commit('SET_SELECTED_COMIDS', data.selectedComIds);
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      try {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      } catch (e) {
        reject(e)
      }
      //没有退出接口 直接删除token回到登录页面
      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}